# Maintainer: David Macek <david.macek.0@gmail.com>

# TODO: include more stuff from tools/?

_realname=nim
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.17.2
pkgrel=1
pkgdesc='Imperative, multi-paradigm, compiled programming language (mingw-w64)'
arch=('any')
url='https://nim-lang.org/'
license=('MIT')
makedepends=('git')
options=(!emptydirs)
source=("${_realname}-${pkgver}.tar.gz"::https://github.com/nim-lang/Nim/archive/v${pkgver}.tar.gz
        "${_realname}-csources-${pkgver}.tar.gz"::https://github.com/nim-lang/csources/archive/v${pkgver}.tar.gz
        "0001-Use-unixy-filenames-even-on-Windows.patch")
sha256sums=('eb8a98c7e576e8d858de98473569a29c539308fc7bb15a086b3f2b73d675f752'
            '7eb28ba7d5a03d02fc1c1fd9089c037de9c058d327fd6e95d599db63d9afa9c8'
            '3010acbe7769ea214dd51f5889e3a26b44925001905deb04b060beaede2578f4')

prepare() {
  cd "${srcdir}"

  rm -rf "${_realname}-${pkgver}/build"
  cp -R "csources-${pkgver}" "${_realname}-${pkgver}/build"

  cd "${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/0001-Use-unixy-filenames-even-on-Windows.patch"
}

build() {
  cd "${srcdir}/${_realname}-${pkgver}"

  pushd build
  sh build.sh --cpu ${MINGW_CHOST}
  popd

  ./bin/nim c koch
  ./koch boot -d:release -d:useGnuReadline

  export PATH="${srcdir}/${_realname}-${pkgver}/bin:$PATH"

  pushd lib
  nim c --app:lib -d:createNimRtl -d:release nimrtl.nim
  popd

  pushd tools
  nim c -d:release nimgrep.nim
  popd
}

package() {
  cd "${srcdir}/${_realname}-${pkgver}"

  export PATH="${srcdir}/${_realname}-${pkgver}/bin:$PATH"

  ./koch install "${pkgdir}"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  # mv "${pkgdir}/nim/bin"/* "${pkgdir}${MINGW_PREFIX}/bin/"
  cp "bin/nim.exe" "${pkgdir}${MINGW_PREFIX}/bin/"
  cp "tools/nimgrep.exe" "${pkgdir}${MINGW_PREFIX}/bin/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib/nim"
  mv "${pkgdir}/nim/lib"/* "${pkgdir}${MINGW_PREFIX}/lib/nim/"
  cp -a "lib/packages" "${pkgdir}${MINGW_PREFIX}/lib/nim/"
  cp "lib/libnimrtl.dll" "${pkgdir}${MINGW_PREFIX}/lib/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/etc"
  mv "${pkgdir}/nim/config"/* "${pkgdir}${MINGW_PREFIX}/etc/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/share/nim/doc"
  cp -r "examples" "web" "${pkgdir}${MINGW_PREFIX}/share/nim/doc/"
  cp -r "doc"/* "${pkgdir}${MINGW_PREFIX}/share/nim/doc/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
  cp "copying.txt" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  # clean up after koch install
  rm -r "${pkgdir}/nim"
}
